package com.five.wisdomEat.controller;

import com.five.wisdomEat.entity.RestaurantOrders;
import com.five.wisdomEat.service.QrCodeService;
import com.five.wisdomEat.until.QRCodeUtil;
import com.google.zxing.WriterException;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping("/home")
public class QrCodeController {
    @Autowired
    private QrCodeService qrCodeService;

    //生成不带logo的二维码到response
    @PostMapping("/qrnologo")
    public ResponseEntity<Resource> qrnologo(String content) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content);
        ByteArrayOutputStream outputStream =new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        byte[] imageBytes = outputStream.toByteArray();
        Resource resource = new ByteArrayResource(imageBytes);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentType(MediaType.IMAGE_JPEG)
                .body(resource);
    }

    @PostMapping("/scan")
    public ResponseEntity<?> scanQrCode(@RequestParam String roNumber) {
        RestaurantOrders orders = qrCodeService.findById(roNumber);
        if (orders == null || orders.getIsValid() == 0) {
//            return ResponseEntity.badRequest().body("Invalid QR code or it has already been scanned.");
            return ResponseEntity.ok("二维码已失效");
        }else {
            qrCodeService.update(orders);
            return ResponseEntity.ok("收货成功，订单完成");
        }

        // 处理扫描逻辑，比如增加扫描次数
//        orders.setIsValid(1); // 或者更新数据库中的“是否有效”字段
//        qrCodeService.update(qrCode);

        // 返回扫描结果或其他逻辑

    }
}
